import {
  useRoutes,
  useLocation,
  useParams,
  useNavigate,
} from "react-router-dom";
import { useEffect, useState } from "react";
import action from "@/store/action/index";
import { EMPTY_ROUTE } from "./routes2";
import { getToken } from "@/utils/auth";
import { useSetupRouterGuard } from "./guard";
import store from "@/store";
import { handleMergeRoutes, hasRoute } from "@/utils/MyFun";
import useGetState from "@/hooks/useGetState";
import * as TYPE from "@/store/action-type";
import { cloneDeep } from "lodash";
import defaultRoutes from "./routes2";
import { useSelector } from "react-redux";

export const useBeforeRouterEnter = () => {
  const completeRouting = cloneDeep(defaultRoutes); //默认路由
  const permissionStore = useSelector((state) => state.permission);
  let [routes, setRoutes, getRoutes] = useGetState(completeRouting); //默认路由

  useEffect(() => {
    if (permissionStore.completeRouting.length === 0) {
      (async function () {
        //异步加载路由
        let route = await addDynamicRoutes(routes);
        if (route) {
          setRoutes(route);
          store.dispatch({
            type: TYPE.PERMISSION_COMPLETEROUTING,
            routes: getRoutes(),
          });
        }
      })();
    }
  }, []);

  useSetupRouterGuard(getRoutes());

  return permissionStore.completeRouting;
};

const RouterView = () => {
  let res_routes = useBeforeRouterEnter();
  return <>{useRoutes(res_routes)}</>;
};

// ! 添加动态路由: 可以由前端生成或后端生成路由
export async function addDynamicRoutes(routes) {
  //获取token
  let token = getToken();

  if (!token) {
    //动态加入EMPTY_ROUTE路由
    if (routes && routes instanceof Array) {
      //防止该函数多次调用，多次添加重复内容
      !hasRoute(routes, EMPTY_ROUTE.name) && routes.push(EMPTY_ROUTE);
    }
    return routes;
  }

  //token存在的情况
  try {
    let { user: userStore } = store.getState((state) => state.user);
    //当用户的user_id不存在的时候，根据token获取用户信息
    !userStore.userInfo?.data?.id &&
      (await store.dispatch(action.user.getUserInfo()));

    //redux-promise可以接受处理后的返回值，即处理reducer中的值
    const accessRoutes = await store.dispatch(
      action.permission.generateRoutesBack()
    );

    //循环判断路由是否存在，不存在就添加（合并路由）
    let new_routes = handleMergeRoutes(accessRoutes.accessRoutes, routes);

    if (hasRoute(new_routes, EMPTY_ROUTE.name)) {
      //移除token不存在时候添加的空界面
      new_routes = new_routes.filter((item) => item.name !== EMPTY_ROUTE.name);
    }

    return new_routes;
  } catch (error) {
    console.error("addDynamicRoutes Error: ", error);
  }
}

export default RouterView;

export const withRouter = (Component) => {
  return function HOC(props) {
    let location = useLocation();
    let params = useParams();
    let navigate = useNavigate();
    return (
      <Component
        {...props}
        location={location}
        params={params}
        navigate={navigate}
      ></Component>
    );
  };
};
